/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.integration.samples.tcpclientserver;

import java.util.Scanner;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.AbstractEndpoint;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.util.TestingUtilities;

/**
 * Demonstrates the use of a gateway as an entry point into the integration flow.
 * The message generated by the gateway is sent over tcp by the outbound gateway
 * to the inbound gateway. In turn the inbound gateway sends the message to an
 * echo service and the echoed response comes back over tcp and is returned to
 * the test case for verification.
 *
 * The test uses explicit transformers to convert the byte array payloads to
 * Strings.
 *
 * Several other samples are provided as JUnit test-cases:
 *
 * <ul>
 *     <li>TcpClientServerDemoWithConversionServiceTest</li>
 *     <li>TcpServerConnectionDeserializeTest</li>
 *     <li>TcpServerCustomSerializerTest</li>
 * </ul>
 *
 * @author Gunnar Hillert
 * @author Artem Bilan
 *
 */
public final class Main {

	/**
	 * Prevent instantiation.
	 */
	private Main() {
	}

	/**
	 * Load the Spring Integration Application Context
	 *
	 * @param args - command line arguments
	 */
	public static void main(final String... args) {

		final Scanner scanner = new Scanner(System.in);

		System.out.println("""

				=========================================================
				                                                        \s
				    Welcome to the Spring Integration                   \s
				          TCP-Client-Server Sample!                     \s
				                                                        \s
				    For more information please visit:                  \s
				    https://www.springsource.org/spring-integration/    \s
				                                                        \s
				=========================================================""");

		final ConfigurableApplicationContext context = Main.setupContext();
		final SimpleGateway gateway = context.getBean(SimpleGateway.class);
		final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);
		final AbstractClientConnectionFactory client = context.getBean(AbstractClientConnectionFactory.class);
		final AbstractEndpoint outGateway = context.getBean("outGateway", AbstractEndpoint.class);

		System.out.print("Waiting for server to accept connections...");
		TestingUtilities.waitListening(crLfServer, 10000L);
		client.setPort(crLfServer.getPort());
		outGateway.start();
		System.out.println("running.\n\n");

		System.out.println("Please enter some text and press <enter>: ");
		System.out.println("\tNote:");
		System.out.println("\t- Entering FAIL will create an exception");
		System.out.println("\t- Entering q will quit the application");
		System.out.print("\n");
		System.out.println("\t--> Please also check out the other samples, " +
				"that are provided as JUnit tests.");
		System.out.println("\t--> You can also connect to the server on port '" + crLfServer.getPort() + "' using Telnet.\n\n");

		while (true) {

			final String input = scanner.nextLine();

			if ("q".equals(input.trim())) {
				break;
			}
			else {
				final String result = gateway.send(input);
				System.out.println(result);
			}
		}

		System.out.println("Exiting application...bye.");
		context.close();
		System.exit(0);

	}

	public static ConfigurableApplicationContext setupContext() {
		return new ClassPathXmlApplicationContext("META-INF/spring/integration/tcpClientServerDemo-context.xml");
	}

}
